package cn.tedu.ymg.product.service.impl;

import cn.tedu.ymg.commons.ex.ServiceException;
import cn.tedu.ymg.commons.pojo.vo.PageData;
import cn.tedu.ymg.commons.util.PageInfoToPageDataConverter;
import cn.tedu.ymg.commons.web.ServiceCode;
import cn.tedu.ymg.product.mapper.MealMapper;
import cn.tedu.ymg.product.mapper.OrderMapper;
import cn.tedu.ymg.product.mapper.UserMapper;
import cn.tedu.ymg.product.pojo.entity.Order;
import cn.tedu.ymg.product.pojo.param.OrderAddNewParam;
import cn.tedu.ymg.product.pojo.param.OrderUpdateInfoParam;
import cn.tedu.ymg.product.pojo.vo.MealStandardVO;
import cn.tedu.ymg.product.pojo.vo.OrderListItemVO;
import cn.tedu.ymg.product.pojo.vo.OrderStandardVO;
import cn.tedu.ymg.product.pojo.vo.UserStandardVO;
import cn.tedu.ymg.product.service.IOrderService;
import cn.tedu.ymg.product.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private IdUtil idUtil;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    MealMapper mealMapper;

    @Override
    public void addNew(OrderAddNewParam orderAddNewParam) {

        log.debug("开始处理【添加订单的业务】，参数",orderAddNewParam);

        //判断用户是否存在
        String username= orderAddNewParam.getUsername();
        Long userId = userMapper.idByUsername(username);
        String phone=userMapper.phoneByUsername(username);
        if (userId == null){
            String message = "新增订单失败，用户不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        //判断套餐是否存在
        Long mealId = orderAddNewParam.getSetMealId();
        MealStandardVO meal = mealMapper.getStandardById(mealId);
        if (meal == null){
            String message = "新增订单失败，套餐不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        //根据用户id和套餐名称生成订单编号
        UUID uuid = UUID.randomUUID();
        String orderNum = userId + "_" + meal.getName() + "_" + uuid.toString();


        //将订单写入到数据库中
        Order order = new Order();
        BeanUtils.copyProperties(orderAddNewParam, order);
        order.setUserId(userId);
        order.setSetMealId(mealId);
        order.setPhone(phone);
        order.setProductCategory(meal.getName());
        order.setOrderNum(orderNum);
        order.setOrderAmount(meal.getPrice());
        order.setCreationTime(LocalDateTime.now());

        int rows = orderMapper.insert(order);
        if (rows !=1){
            String message = "添加订单失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的订单数据写入到数据库，完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除订单】的业务，参数：{}", id);
        Order order = orderMapper.selectById(id);
        if (order ==null){
            String message = "删除订单失败，Id不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }

        int rows = orderMapper.deleteById(id);
        if (rows!=1){
            String message = "删除订单失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("从数据库删除订单，完成！");
    }

    @Override
    public void updateInfoById(Long id, OrderUpdateInfoParam orderUpdateInfoParam) {

        log.debug("开始处理【修改订单】的业务，ID:{},新数据：{}", id, orderUpdateInfoParam);

        //检查订单是否存在，如果不存在，则抛出异常
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = orderMapper.selectCount(queryWrapper);
        log.debug("根据示例ID统计匹配的订单数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改订单失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        //执行修改
        Order order = new Order();
        BeanUtils.copyProperties(orderUpdateInfoParam, order);
        order.setId(id);
        int rows = orderMapper.updateById(order);
        if (rows!=1){
            String message = "修改订单失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("从数据库修改订单，完成！");
    }

    @Override
    public OrderStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询订单】的业务，参数：{}", id);
        OrderStandardVO queryResult = orderMapper.getStandardById(id);
        if (queryResult==null){
            String message = "查询订单失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public PageData<OrderListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<OrderListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询订单列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<OrderListItemVO> list =  orderMapper.list();
        PageInfo<OrderListItemVO> pageInfo = new PageInfo<>(list);
        PageData<OrderListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        return pageData;
    }

}
